package com.ouroboroswiki.core.content.image;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;

import com.ouroboroswiki.core.AbstractProxiedContent;
import com.ouroboroswiki.core.Content;
import com.ouroboroswiki.core.ContentException;
import com.ouroboroswiki.core.ContentUtil;

public class ScalingImageContentProxy extends AbstractProxiedContent {
	
	private Dimension maxDimension;
	private Map<?,?> hints;
	
	public ScalingImageContentProxy( 
			Content proxied, 
			Dimension maxDimension,
			Map<?,?> hints
	) {
		super( proxied );
		this.maxDimension = maxDimension;
		this.hints = hints;
	}

	@Override
	public void write(OutputStream outs) throws IOException, ContentException {
		InputStream input = ContentUtil.openInputStream(proxied);
		BufferedImage image = ImageIO.read(input);
		String formatName = null;
		String mimeType = this.proxied.getMimeType();
		Iterator<ImageReader> readers = ImageIO.getImageReadersByMIMEType(mimeType);
		while( readers.hasNext() && formatName == null ) {
			ImageReader reader = readers.next();
			formatName = reader.getFormatName();
		}
		int width = image.getWidth();
		int height = image.getHeight();
		if( maxDimension.width < width ) {
			height = Math.max(1, (height * maxDimension.width) / width);
			width = maxDimension.width;
		}
		if( maxDimension.height < height ) {
			width = Math.max(1, (width * maxDimension.height) / height);
			height = maxDimension.height;
		}
		BufferedImage scaled = new BufferedImage(
				width, 
				height, 
				BufferedImage.TYPE_INT_ARGB
		);
		Graphics2D g = (Graphics2D)scaled.getGraphics();
		g.setRenderingHints(hints);
		g.drawImage( image, 0, 0, width, height, null );
		ImageIO.write(scaled, formatName, outs);
	}
}
